<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>测试响应式的实现</title>
  </head>

  <body>
    <div id="app"></div>

    <script>
      const obj = {};

      function defineReactive(obj, key, val) {
        // 对传入obj进行访问拦截
        Object.defineProperty(obj, key, {
          get() {
            console.log("get " + key);
            return val;
          },
          set(newVal) {
            if (newVal !== val) {
              console.log("set " + key + ":" + newVal);
              val = newVal;
              // 在拦截器里面添加更新函数
              update();
            }
          },
        });
      }
      // 简单的数据驱动，初始显示foo，foo的值改变就会引起innerHTML的改变
      function update() {
        app.innerText = obj.foo;
      }

      defineReactive(obj, "foo", "");
      obj.foo = new Date().toLocaleTimeString();

      setInterval(() => {
        obj.foo = new Date().toLocaleTimeString();
      }, 1000);
    </script>
  </body>
</html>
